# -*- coding: utf-8 -*-

from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse

from ops.cmdb.models import Servers
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
import base64


class ServersSerializer(CustomModelSerializer):
    """
    字典-序列化器
    """

    # 重写save方法，对password字段加密
    # def save(self, **kwargs):
    #     data = super().save(**kwargs)
    #     obj = Servers.objects.get(id=data.id)
    #     print(obj)
    #     if obj.password != data.password:
    #         print('更新服务器密码')
    #         data.password = password_base64.decode('utf-8')
    #     else:
    #         print('服务器密码未变化，放弃更新')
    #         print(obj.password)
    #         data.password = obj.password
    #     data.password = base64.b64encode(data.password.encode('utf-8'))
    #     data.save()
    #     return data

    class Meta:
        model = Servers
        fields = "__all__"
        read_only_fields = ["id"]


class ServersViewSet(CustomModelViewSet):
    """
    字典管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Servers.objects.all()
    serializer_class = ServersSerializer
    extra_filter_backends = []
    permission_classes = []
    search_fields = ["devices_name", "devices_num", "devices_type", "remark", "devices_localip", "devices_interip"]

    # 重写update方法，当password相同时忽略
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        data = request.data
        obj = Servers.objects.get(id=data.get('id'))
        if obj.password != data.get('password'):
            password_base64 = base64.b64encode(data.get('password').encode('utf-8')).decode('utf-8')
            data['password'] = password_base64
        else:
            data['password'] = obj.password

        serializer = self.get_serializer(instance, data=data, request=request, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        return DetailResponse(data=serializer.data, msg="更新成功")


